package top.zhouze.common.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import lombok.AllArgsConstructor;
import lombok.Getter;
import timber.log.Timber;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileLoggingTree extends Timber.Tree {

    @Getter
    @AllArgsConstructor
    public enum LogLevel {
        VERBOSE("VERBOSE",2),
        DEBUG("DEBUG",3),
        INFO("INFO",4),
        WARN("WARN",5),
        ERROR("ERROR",6),
        FATAL("FATAL",7);
        private final String levelName;
        private final int priority;
    }

    private final String logDirPath;
    private static int currentLevel = 4;

    public static void setCurrentLevel(int currentLevel) {
        FileLoggingTree.currentLevel = currentLevel;
    }

    public static void setCurrentLevel(LogLevel currentLevel) {
        FileLoggingTree.currentLevel = currentLevel.getPriority();
    }

    public FileLoggingTree(Context context) {
        logDirPath = context.getCacheDir().toString();
        createDir(logDirPath);
    }

    public FileLoggingTree(String logDirPath) {
        this.logDirPath = logDirPath;
        createDir(logDirPath);
    }

    /**
     * 使用Timber自定义吧log信息存储到文件中
     * 其中String CacheDiaPath = context.getCacheDir().toString();
     */
    @Override
    protected void log(int priority, String tag, String message, Throwable t) {
        if (currentLevel <= priority) {
            if (TextUtils.isEmpty(logDirPath)) {
                return;
            }
            String time = getTime("yyyy-MM-dd HH:mm:ss.SSS");
            long threadId = Thread.currentThread().getId();
            String levelName = LogLevel.values()[priority-2].getLevelName();
            String msg = String.format("%s %s %s %s %s",time,levelName,threadId,getTag(tag),message);
            try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(getLogFileFile(),true));) {
                bufferedWriter.write(msg);
                bufferedWriter.newLine();
            } catch (IOException e) {
                Log.w(getTag(tag),e.getMessage());
            }
        }
    }

    private String getLogFileFile() {
        return logDirPath + "/"+getTime("yyyy-MM-dd")+"-log.txt";
    }

    @SuppressLint("SimpleDateFormat")
    private String getTime(String format) {
        return new SimpleDateFormat(format).format(new Date());
    }

    private String getTag(String tag) {
        String tag1 = tag;
        if (tag1 != null) {
            return tag1;
        } else {
            StackTraceElement[] stackTrace = (new Throwable()).getStackTrace();
            if (stackTrace.length <= 6) {
                throw new IllegalStateException("Synthetic stacktrace didn't have enough elements: are you using proguard?");
            } else {
                tag1 = stackTrace[6].getClassName().replaceAll("[\\w|.]+\\.","");
            }
        }
        return tag1;
    }

    private void createDir(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}